import { createSlice } from "@reduxjs/toolkit";

const orderSlice = createSlice({
  name: "order",
  initialState: {
    psgArr: [
      { name: "蒲熠星", idcard: "510722199404208076", ticketType: "成人票" },
      { name: "郭文韬", idcard: "630121199404104718", ticketType: "成人票" },
    ],
    setArr: [],
  },
  reducers: {
    addPsg(state, action) {
      state.psgArr.push(action.payload);
    },
    removePsg(state, action) {
      state.psgArr = state.psgArr.filter((item, i) => i !== action.payload);
    },
    addSeat(state, action) {
      //判断传入 action.payload 是否被选中
      //被选中，移除
      //未被选中，添加
      //欲添加，先判断座位满否
      //1.未满，直接push
      //2.满则先移后push
      if (state.setArr.includes(action.payload)) {
        //移出座位
        state.setArr = state.setArr.filter((item) => item !== action.payload);
      } else {
        if (state.setArr.length >= state.psgArr.length) {
          //选满了 见 2
          state.setArr.shift();
          state.setArr.push(action.payload);
        } else {
          //未满 见 1
          state.setArr.push(action.payload);
        }
      }
    },
    addArr(state, action) {
      action.payload.forEach((item) => {
        if (!state.psgArr.find((x) => x.idcard === item.idcard)) {
          state.psgArr.push(item);
        }
      });
    },
  },
});
export const { addPsg, removePsg, addSeat,addArr } = orderSlice.actions;
export default orderSlice.reducer;
